﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using OrderingPlatform.DalService.CommonManage;
using OrderingPlatform.Model;
using OrderingPlatform.MvcExtension;

namespace OrderingPlatform.BllService.CommonManage
{
    public class FileService
    {
        private readonly FileDal _fileDal = new FileDal();

        public Guid SaveFile(HttpPostedFileBase uploadFile, string directory)
        {
            var rootpath = StringExtension.GetRootPath();
            var filePath = string.Format("\\Upload\\{0}\\", directory);
            var userId = UserService.UserBaeService.GetUserModel().UserId;
            filePath = filePath + userId.ToString() + "\\";

            var bytes = new byte[uploadFile.InputStream.Length];
            var dir = new System.IO.DirectoryInfo(rootpath+filePath);
            //判断文件夹否存在,不存在则创建 
            if (!dir.Exists)
            {
                dir.Create();
            }
            var fileName = uploadFile.FileName;
            var ex = Path.GetExtension(fileName);
            var orginFileName = fileName.Substring(0,fileName.LastIndexOf('.')) + DateTime.Now.ToString("yyyyMMddHHmmss") + ex;
            uploadFile.SaveAs(rootpath+filePath + orginFileName);
            var origId = SaveFile(bytes, fileName, filePath + orginFileName);
            var thumbnailPath =rootpath+ filePath + "thumbnail" + orginFileName;
            var newbytes = MakeSmallImg(uploadFile.InputStream, 120, 120, thumbnailPath);
            return origId;
        }
        public Guid SaveFile(byte[] bytes, string fileName, string path)
        {
            var file = new OrderingPlatform.Infrastructure.File()
            {
                FileId = Guid.NewGuid(),
                CreateDate = DateTime.Now,
                FileName = fileName,
                Length = bytes.Length,
                State = true,
                Path = path
            };

            _fileDal.SaveFile(file);
            return file.FileId;
        }

        public DownlaodFileModel GetFileStream(Guid fileId, bool hasThumbnail = false)
        {
            var model = GetFile(fileId);
            var path = model.Path;
            if (hasThumbnail)
            {
                path = model.Path.Substring(0, model.Path.LastIndexOf('\\') + 1) + "thumbnail" +
                model.Path.Substring(model.Path.LastIndexOf('\\') + 1, model.Path.Length - model.Path.LastIndexOf('\\') - 1);
            }
            path = StringExtension.GetRootPath() + path;
            var result = new DownlaodFileModel()
                {
                    FileName = model.FileName,
                    Image = GetPictureData(path)

                };
            return result;
        }

        public DownlaodFileModel GetMiddleFileStream(Guid fileId)
        {
            
            var model = GetFile(fileId);
            var path = model.Path;
           
            path = StringExtension.GetRootPath() + path;
            var fs = new FileStream(path, FileMode.Open);//可以是其他重载方法 
            var byteimg = MakeSmallImg(fs,280,200);
            var result = new DownlaodFileModel()
            {
                FileName = model.FileName,
                Image = byteimg

            };
            return result;
        }

        public DownlaodFileModel GetSmallFileStream(Guid fileId)
        {
            var model = GetFile(fileId);
            var path =  model.Path.Substring(0, model.Path.LastIndexOf('\\') + 1) + "thumbnail" +
                            model.Path.Substring(model.Path.LastIndexOf('\\') + 1, model.Path.Length - model.Path.LastIndexOf('\\') - 1);
            path = StringExtension.GetRootPath() + path;
            var fs = new FileStream(path, FileMode.Open);//可以是其他重载方法 
            var byteimg = MakeSmallImg(fs, 50, 50);
            var result = new DownlaodFileModel()
            {
                FileName = model.FileName,
                Image = byteimg

            };
            return result;
        }

        public byte[] GetPictureData(string imagepath)
        {
            try
            {
                var fs = new FileStream(imagepath, FileMode.Open, System.IO.FileAccess.Read, FileShare.ReadWrite);
                //可以是其他重载方法 
                var byData = new byte[fs.Length];
                fs.Read(byData, 0, byData.Length);
                fs.Close();
                fs.Dispose();
                return byData;
            }
            catch
            {
                return null;
            }
        }

        public OrderingPlatform.Infrastructure.File GetFile(Guid fileId)
        {
            return _fileDal.GetFile(fileId);
        }

        public static byte[] MakeSmallImg(System.IO.Stream fromFileStream, System.Double templateWidth, System.Double templateHeight, string thumbnailPath)
        {
            //从文件取得图片对象，并使用流中嵌入的颜色管理信息 
            var myImage = System.Drawing.Image.FromStream(fromFileStream, true);
            //缩略图宽、高 
            System.Double newWidth = myImage.Width, newHeight = myImage.Height;
            //宽大于模版的横图 
            if (myImage.Width > myImage.Height || myImage.Width == myImage.Height)
            {
                if (myImage.Width > templateWidth)
                {
                    //宽按模版，高按比例缩放 
                    newWidth = templateWidth;
                    newHeight = myImage.Height * (newWidth / myImage.Width);
                }
            }
            //高大于模版的竖图 
            else
            {
                if (myImage.Height > templateHeight)
                {
                    //高按模版，宽按比例缩放 
                    newHeight = templateHeight;
                    newWidth = myImage.Width * (newHeight / myImage.Height);
                }
            }
            //取得图片大小 
            var mySize = new Size((int)newWidth, (int)newHeight);
            if (mySize.Width <= 0)
                mySize.Width = 1;
            if (mySize.Height <= 0)
                mySize.Height = 1;
            //新建一个bmp图片 
            var bitmap = new System.Drawing.Bitmap(mySize.Width, mySize.Height);
            //新建一个画板 
            var g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空一下画布 
            g.Clear(Color.White);
            //在指定位置画图 
            g.DrawImage(myImage, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            new System.Drawing.Rectangle(0, 0, myImage.Width, myImage.Height),
            System.Drawing.GraphicsUnit.Pixel);
            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            var ms = new MemoryStream();
            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            var byteImage = new Byte[ms.Length];
            byteImage = ms.ToArray();

            g.Dispose();
            myImage.Dispose();
            bitmap.Dispose();
            return byteImage;
        }

        public static byte[] MakeSmallImg(System.IO.FileStream fromFileStream, System.Double templateWidth, System.Double templateHeight)
        {
            try
            {
                //从文件取得图片对象，并使用流中嵌入的颜色管理信息 
                var myImage = System.Drawing.Image.FromStream(fromFileStream, true);
                //缩略图宽、高 
                System.Double newWidth = myImage.Width, newHeight = myImage.Height;
                //宽大于模版的横图 
                if (myImage.Width > myImage.Height || myImage.Width == myImage.Height)
                {
                    if (myImage.Width > templateWidth)
                    {
                        //宽按模版，高按比例缩放 
                        newWidth = templateWidth;
                        newHeight = myImage.Height*(newWidth/myImage.Width);
                    }
                }
                    //高大于模版的竖图 
                else
                {
                    if (myImage.Height > templateHeight)
                    {
                        //高按模版，宽按比例缩放 
                        newHeight = templateHeight;
                        newWidth = myImage.Width*(newHeight/myImage.Height);
                    }
                }
                //取得图片大小 
                var mySize = new Size((int) newWidth, (int) newHeight);
                if (mySize.Width <= 0)
                    mySize.Width = 1;
                if (mySize.Height <= 0)
                    mySize.Height = 1;
                //新建一个bmp图片 
                var bitmap = new System.Drawing.Bitmap(mySize.Width, mySize.Height);
                //新建一个画板 
                var g = System.Drawing.Graphics.FromImage(bitmap);
                //设置高质量插值法 
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                //设置高质量,低速度呈现平滑程度 
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //清空一下画布 
                g.Clear(Color.White);
                //在指定位置画图 
                g.DrawImage(myImage, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                            new System.Drawing.Rectangle(0, 0, myImage.Width, myImage.Height),
                            System.Drawing.GraphicsUnit.Pixel);
                var ms = new MemoryStream();
                bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                var byteImage = new Byte[ms.Length];
                byteImage = ms.ToArray();

                g.Dispose();
                myImage.Dispose();
                bitmap.Dispose();
                return byteImage;
            }
            catch
            {
                return null;
            }
        }
    }
}
